package com.zl.learning.xml.test;

import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.File;
import java.io.IOException;


public class ReadXML {
	private static Document doc = null;
	/**
	 * @param args
	 */
	public static void readXML(String xmlPath){
		try {
			XPath xpathEngine = XPathFactory.newInstance().newXPath();
			InputSource xmlSource = new InputSource(xmlPath); 
			String xpathExpression1 = "/Root/Header"; 
			String xpathExpression2 = "/Root/content"; 
			String result = xpathEngine.evaluate(xpathExpression1, xmlSource);
			String result2 = xpathEngine.evaluate(xpathExpression2, xmlSource);
			
			System.out.println(result);
			System.out.println(result2);
		} catch (XPathExpressionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	public static void readXMLByDom(String xmlPath){
		init(xmlPath);
		Element element = doc.getDocumentElement();    
		System.out.println("Root element: " + element.getTagName());
		
		NodeList nodeList = doc.getElementsByTagName("person");    
		System.out.println("book节点链的长度:" + nodeList.getLength());    
		  
		Node fatherNode = nodeList.item(0);    
		System.out.println("父节点为:" + fatherNode.getNodeName());    
		  
		//get attribute of father node 
		NamedNodeMap attributes = fatherNode.getAttributes(); 
		for (int i = 0; i < attributes.getLength(); i++) {
			Node attribute = attributes.item(i);    
			System.out.println("book的属性名为:" + attribute.getNodeName()    
			+ " 相对应的属性值为:" + attribute.getNodeValue());
		}
		NodeList childNodes = fatherNode.getChildNodes();    
		System.out.println(childNodes.getLength());    
		for (int j = 0; j < childNodes.getLength(); j++) {
			Node childNode = childNodes.item(j);    
			// 如果这个节点属于Element ,再进行取值    
			if (childNode instanceof Element) {    
			// System.out.println("子节点名为:"+childNode.getNodeName()+"相对应的值为"+childNode.getFirstChild().getNodeValue());    
				System.out.println("子节点名为:" + childNode.getNodeName()    
						+ "相对应的值为" + childNode.getFirstChild().getNodeValue());    
			}  
		}
	}
	public static void init(String xmlPath){
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();    
			DocumentBuilder db = dbf.newDocumentBuilder();
			doc = db.parse(new File(xmlPath));
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//readXML("c:/Bill/temp/test.xml");
		readXMLByDom("person.xml");
	}

}

